package com.feihong.txgw.ui.activity.user;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.KeyboardUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.adapter.LocationSortAdapter;
import com.feihong.txgw.inter.contract.location.ILocationContract;
import com.feihong.txgw.inter.listener.location_city.HotCityListener;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.bean.location.LocationInfo;
import com.feihong.txgw.model.bean.user.CityInfo;
import com.feihong.txgw.model.bean.user.SortModel;
import com.feihong.txgw.tx_precenter.LocationMainPrecenter;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.CharacterParser;
import com.feihong.txgw.utils.ClearEditText;
import com.feihong.txgw.utils.LocationCallBack;
import com.feihong.txgw.utils.LocationTools;
import com.feihong.txgw.utils.PinyinComparator;
import com.feihong.txgw.utils.SideBar;
import com.feihong.txgw.utils.UserLoginInfo;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 定位界面
 */
public class LocationActivty extends BaseMVPCompateActivity<ILocationContract.AbLocationMainPrecenter> implements ILocationContract.ILocationMainView {


    /**
     * 地理信息显示button
     */
    @BindView(R.id.tv_btn_location)
    TextView btn_show;
    @BindView(R.id.iv_back)
    ImageButton btnBack;
    @BindView(R.id.et_input_citys)
    ClearEditText et_input_citys;
    /**
     * listview
     */
    @BindView(R.id.country_lvcountry)
    ListView countryLvcountry;
    /**
     * 检索显示 dialog
     */
    @BindView(R.id.dialog)
    TextView dialog;
    /**
     * 侧边栏
     */
    @BindView(R.id.sidrbar)
    SideBar sidrbar;
    @BindView(R.id.tv_pagetitle)
    TextView txtitle;

    @BindView(R.id.tv_edtext_show)
    TextView tv_new_location;
    private Intent intent;

    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectErrorLayout;

    @BindView(R.id.location_content_layout)
    LinearLayout mLocationContentLayout;

    private LocationSortAdapter locationSortAdapter;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private SortModel.DataBean SourceDateList;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    CityInfo cityInfo;
    private String locationText;

    private InputMethodManager imm;
    private List<SortModel.DataBean.HotCityBean> mHotCityBeans = new ArrayList<>();
    /**
     * 新的经纬度  城市(点击定位时使用
     */
    private String newCity_location, newCityCode_location;
    private Double newCityLat_location, newCityLog_location;

    @BindView(R.id.lay_loading)
    RelativeLayout mLoadLayout;

    @BindView(R.id.activity_location_status_layout)
    View mStatusView;

    private static int CITYDATA_FIRST_SUCCESS = 1;
    private static int CITYDATA_FIRST_ERROR = 2;
    private static int CITYDATA_PARSE = 3;
    private static final String REQUEST_DATA_WHAT = "REQUEST";
    private static final String PARSE_DATA_WHAT = "PARSE";
    /**
     * 判断是从哪个界面跳转过来  如果是空的话 则是从首页跳转而来
     * 如果是从首页跳转过来的  则需要修改本地的用户位置信息
     * 如果不是从首页跳转过来的  则 只需要返回选择的位置信息
     */
    public static final String FROM_WHERE_KEY = "FROM_WHERE_KEY";
    private boolean isFromHome = false;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (activityIsDestory()) {
                return;
            }
            if (msg.what == CITYDATA_FIRST_SUCCESS) {
                Bundle bundle = msg.getData();
                SortModel aBean = (SortModel) bundle.get(REQUEST_DATA_WHAT);
                mLocationContentLayout.setVisibility(View.VISIBLE);
                mConnectErrorLayout.setVisibility(View.GONE);
                mLoadLayout.setVisibility(View.GONE);
                SourceDateList = aBean.getData();
                locationSortAdapter.updateListView(SourceDateList);
                mHotCityBeans = SourceDateList.getHot_city();
                locationSortAdapter.setHotCityListener(hotCityListener);
            } else if (msg.what == CITYDATA_FIRST_ERROR) {
                    showSystemToast("数据解析失败！");
                    mLoadLayout.setVisibility(View.GONE);
                    mLocationContentLayout.setVisibility(View.GONE);
                    mConnectErrorLayout.setVisibility(View.VISIBLE);
            } else if (msg.what == CITYDATA_PARSE) {
                mLoadLayout.setVisibility(View.GONE);
                Bundle bundle = msg.getData();
                SortModel.DataBean filterDateList = (SortModel.DataBean) bundle.get(PARSE_DATA_WHAT);
                locationSortAdapter.updateListView(filterDateList);
            }
        }
    };

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_location;
    }

    public static final String DEFAULT_CITY_SHOW = "DEFAULT_CITY_SHOW";

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        setSpecificTitleLayout(mStatusView);
        intent = getIntent();
        String fromWhere = intent.getStringExtra(FROM_WHERE_KEY);
        isFromHome = TextUtils.isEmpty(fromWhere) ? true : false;
        cityInfo = UserLoginInfo.getUserCityInfo();

        txtitle.setText("定位当前位置");

        imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (isFromHome) {
            locationText = cityInfo.getCityName();
            newCityCode_location = cityInfo.getCityCode();
            newCityCode_location = cityInfo.getCityCode();
            newCityLat_location = Double.valueOf(cityInfo.getLatitude());
            newCityLog_location = Double.valueOf(cityInfo.getLongitude());
        } else {
            locationText = intent.getStringExtra(DEFAULT_CITY_SHOW);
        }
        newCity_location = locationText;
        if (!TextUtils.isEmpty(locationText)) {
            btn_show.setText(locationText);
        } else {
            findLocation();
        }
        // 中央显示所选区域字母
        sidrbar.setTextView(dialog);
        //实例化一个拼音转换类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();

        sidrbar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {

                //该字母首次出现的位置
                int position = locationSortAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    countryLvcountry.setSelection(position);
                }
            }
        });

        locationSortAdapter = new LocationSortAdapter(LocationActivty.this);
        if (!isFromHome) {
            locationSortAdapter.setShowHotCity(false);
        }
        countryLvcountry.setAdapter(locationSortAdapter);
        countryLvcountry.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //这里要利用adapter.getItem(position)来获取当前position所对应的对象

                SortModel.DataBean.CityBean item = (SortModel.DataBean.CityBean) locationSortAdapter.getItem(position);
                if (isFromHome) {
                    CityInfo currenInfo = UserLoginInfo.getUserCityInfo();
                    if (currenInfo != null) {
                        cityInfo = currenInfo;
                    }
                    Log.i(TAG, "onItemClick: " + item.toString());
                    RequestLocation(item.getRegion_id());
                    if (!item.getAreacode().equals(cityInfo.getCityCode())) {
                        cityInfo.setLatitude(item.getLatitude());
                        cityInfo.setLongitude(item.getLongitude());
                        cityInfo.setCityCode(item.getAreacode());
                        cityInfo.setCityName(item.getRegion_name());
                        UserLoginInfo.setUserCityInfo(cityInfo);
                    }
                    intent.putExtra("city", cityInfo.getCityName());
                    intent.putExtra("Longitude", cityInfo.getLongitude());
                    intent.putExtra("Latitude", cityInfo.getLatitude());
                    intent.putExtra("CityCode", cityInfo.getCityCode());
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    intent.putExtra("city", item.getRegion_name());
                    intent.putExtra("Longitude", item.getLongitude());
                    intent.putExtra("Latitude", item.getLatitude());
                    intent.putExtra("CityCode", item.getAreacode());
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });

        et_input_citys.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }
        });

        et_input_citys.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                KeyboardUtils.hideSoftInput(LocationActivty.this);
                return true;
            }
        });
    }


    @Override
    public void bindData() {
        mLoadLayout.setVisibility(View.VISIBLE);
        mPresenter.loadAllCity();
    }

    HotCityListener hotCityListener = new HotCityListener() {
        @Override
        public void setHotCityListtener(CityInfo cityInfo) {
            RequestLocation(cityInfo.getCityCode());
            intent.putExtra("city", cityInfo.getCityName());
            intent.putExtra("Longitude", cityInfo.getLongitude());
            intent.putExtra("Latitude", cityInfo.getLatitude());
            intent.putExtra("CityCode", cityInfo.getCityCode());
            setResult(RESULT_OK, intent);
            finish();
        }
    };

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @OnClick({R.id.iv_back, R.id.tv_edtext_show, R.id.tv_btn_location, R.id.re_query_data_layout})
    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                if (TextUtils.isEmpty(newCity_location)) {
                    finish();
                } else {
                    intent.putExtra("city", newCity_location);
                    intent.putExtra("Longitude", String.valueOf(newCityLog_location));
                    intent.putExtra("Latitude", String.valueOf(newCityLat_location));
                    intent.putExtra("CityCode", newCityCode_location);
                    setResult(RESULT_OK, intent);
                    finish();
                }
                break;
            case R.id.tv_edtext_show:
                mLoadLayout.setVisibility(View.VISIBLE);
                findLocation();
                break;
            case R.id.tv_btn_location:

                intent.putExtra("city", newCity_location);
                intent.putExtra("Longitude", String.valueOf(newCityLog_location));
                intent.putExtra("Latitude", String.valueOf(newCityLat_location));
                intent.putExtra("CityCode", newCityCode_location);
                setResult(RESULT_OK, intent);
                finish();
                break;
            case R.id.re_query_data_layout:
                mConnectErrorLayout.setVisibility(View.GONE);
                bindData();
                break;
            default:
                break;
        }
    }

    //定位
    private void findLocation() {
        LocationTools locationTools = new LocationTools(getActivity(), new LocationCallBack() {
            @Override
            public void successGetLocation(LocationInfo info) {
                mLoadLayout.setVisibility(View.GONE);
                if (info != null) {

                    cityInfo.setCityCode(info.getCityCode());
                    cityInfo.setCityName(info.getCity());
                    cityInfo.setLatitude(info.getLatitude() + "");
                    cityInfo.setLongitude(info.getLongitude() + "");
                    if (btn_show != null) {
                        btn_show.setText(info.getCity());
                    }
                    newCity_location = info.getCity();
                    newCityCode_location = info.getCityCode();
                    newCityLat_location = info.getLatitude();
                    newCityLog_location = info.getLongitude();

                    if (UserLoginInfo.setUserCityInfo(cityInfo)) {
                    } else {
                        showSystemToast("设置定位信息失败！");
                    }
                } else {
                    showSystemToast("定位失败,请手动选择城市");
                }
            }

            @Override
            public void error(String error) {
                mLoadLayout.setVisibility(View.GONE);
                switch (error) {
                    case "4":
                    case "5":
                        showSystemToast("定位失败,请检查网络");
                        break;
                    case "12":
                        showSystemToast("请在设备的设置中开启app的定位权限");
                        break;
                    case "13":
                        showSystemToast("定位失败,请检查网络、GPS是否开启以及定位权限是否开启");
                        break;
                    case "14":
                        showSystemToast("定位失败,请到相对开阔的露天场所再次尝试");
                        break;
                    case "18":
                        showSystemToast("定位失败,建议手机关闭飞行模式，并打开WIFI开关");
                        break;
                    case "19":
                        showSystemToast("定位失败,建议手机插上sim卡，打开WIFI开关");
                        break;
                    default:
                        showSystemToast("定位失败,请手动选择城市");
                        break;
                }
            }
        });
        locationTools.startLocation();
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr //
     */
    private void filterData(String filterStr) {
        SortModel.DataBean filterDateList = new SortModel.DataBean();
        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
            if (!isFromHome) {
                locationSortAdapter.setShowHotCity(false);
            } else {
                locationSortAdapter.setShowHotCity(true);
            }
            locationSortAdapter.updateListView(filterDateList);
        } else {
            mLoadLayout.setVisibility(View.VISIBLE);
            locationSortAdapter.setShowHotCity(false);
            mCityParseThread = new CityParseThread(filterDateList, filterStr);
            mCityParseThread.start();
        }
    }

    @Override
    public void loadAllCityResult(SortModel result) {
        if (activityIsDestory()) {
            return;
        }
        mLocationContentLayout.setVisibility(View.VISIBLE);
        mConnectErrorLayout.setVisibility(View.GONE);
        mLoadLayout.setVisibility(View.GONE);
        SourceDateList = result.getData();
        locationSortAdapter.updateListView(SourceDateList);
        mHotCityBeans = SourceDateList.getHot_city();
        locationSortAdapter.setHotCityListener(hotCityListener);
        mLoadLayout.setVisibility(View.GONE);
//        parseData(result);
    }

    @Override
    public void loadDataComplated() {

    }

    @Override
    public void loadDataError() {
        mLoadLayout.setVisibility(View.GONE);
        mLocationContentLayout.setVisibility(View.GONE);
        mConnectErrorLayout.setVisibility(View.VISIBLE);
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return LocationMainPrecenter.create();
    }

    class MyRequestRunnable extends Thread {

        private String result;

        public MyRequestRunnable(String result) {
            this.result = result;
        }

        @Override
        public void run() {
            try {
                SortModel aBean = JSON.parseObject(result, SortModel.class);
                if (aBean != null && aBean.getCode() == 200) {
                    Message message = Message.obtain();
                    Bundle bundle = new Bundle();
                    bundle.putParcelable(REQUEST_DATA_WHAT, aBean);
                    message.setData(bundle);
                    message.what = CITYDATA_FIRST_SUCCESS;
                    mHandler.sendMessage(message);
                } else {
                    mHandler.sendEmptyMessage(CITYDATA_FIRST_ERROR);
                }

            } catch (Exception ex) {
                mHandler.sendEmptyMessage(CITYDATA_FIRST_ERROR);
            }
        }
    }

    class CityParseThread extends Thread {
        private SortModel.DataBean filterDateList;
        private String filterStr;

        public CityParseThread(SortModel.DataBean data, String str) {
            filterDateList = data;
            filterStr = str;
        }

        @Override
        public void run() {
            List<SortModel.DataBean.CityBean> cityBeans = new ArrayList<>();
            List<SortModel.DataBean.CityBean> cities = SourceDateList.getCity();
            for (SortModel.DataBean.CityBean sortModel : cities) {
                String name = sortModel.getRegion_name();
                if (name.contains(filterStr) || characterParser.getSelling(name).startsWith(filterStr)) {
                    cityBeans.add(sortModel);
                    filterDateList.setCity(cityBeans);
                }
            }
            filterDateList.setHot_city(mHotCityBeans);
            Message message = Message.obtain();
            Bundle bundle = new Bundle();
            bundle.putParcelable(PARSE_DATA_WHAT, filterDateList);
            message.setData(bundle);
            message.what = CITYDATA_PARSE;
            mHandler.sendMessage(message);
        }
    }

    private MyRequestRunnable mReqRunnable;
    private CityParseThread mCityParseThread;

    private void parseData(final String result) {
        mReqRunnable = new MyRequestRunnable(result);
        mReqRunnable.start();
    }

    @Override
    protected void onDestroy() {
        try {
            if (mReqRunnable != null) {
                mReqRunnable.join();
                mReqRunnable.interrupt();
            }
            if (mCityParseThread != null) {
                mCityParseThread.join();
                mCityParseThread.interrupt();
            }
        } catch (Exception ex) {

        }
        if (mHandler != null && mHandler.getLooper() == Looper.getMainLooper()) {
            mHandler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }

    public void RequestLocation(String regionID) {
        mPresenter.countCityHits(regionID);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            chackActivityState();
            intent.putExtra("city", newCity_location);
            intent.putExtra("Longitude", String.valueOf(newCityLog_location));
            intent.putExtra("Latitude", String.valueOf(newCityLat_location));
            intent.putExtra("CityCode", newCityCode_location);
            setResult(RESULT_OK, intent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

//    @Override
//    public void onBackPressedSupport() {
//        super.onBackPressedSupport();
//        if (!TextUtils.isEmpty(newCity_location)) {
//            intent.putExtra("city", newCity_location);
//            intent.putExtra("Longitude", String.valueOf(newCityLog_location));
//            intent.putExtra("Latitude", String.valueOf(newCityLat_location));
//            intent.putExtra("CityCode", newCityCode_location);
//            setResult(1, intent);
//        }
//        finish();
//    }
}
